import asyncio
import websockets
import subprocess
import numpy as np
from scipy.io.wavfile import write

async def send_audio(file_path):
    uri = "ws://202.114.212.193:50512/audio"
    
    # Use ffmpeg to convert the audio file to the required format
    cmd = [
        "ffmpeg",
        "-i", file_path,
        "-f", "s16le",
        "-ac", "1",
        "-acodec", "pcm_s16le",
        "-ar", "16000",  # Assuming SAMPLE_RATE is 16000
        "-"
    ]
    
    try:
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        raw_audio, _ = process.communicate()
        print(f"Raw audio length: {len(raw_audio)}")
        print(f"Raw audio sample: {raw_audio[:100]}")
    except Exception as e:
        print(f"Error converting audio file: {e}")
        return
    
    async with websockets.connect(uri) as websocket:
        # Send the entire audio data
        await websocket.send(raw_audio)
        
        # Indicate the end of the audio data
        await websocket.send(b'')
        
        # Receive and print the transcription result
        try:
            audio_data = bytearray()
            while True:
                message = await websocket.recv()
                if isinstance(message, str):
                    print("Transcription:", message)
                elif isinstance(message, bytes):
                    if len(message) == 0:
                        break
                    audio_data.extend(message)
            
            # Convert bytearray to numpy array
            audio_np = np.frombuffer(audio_data, dtype=np.float32)
            
            # Save the received audio data to a file
            write("received_audio.wav", 24000, audio_np)
            print("Received audio and saved to received_audio.wav")
        except websockets.exceptions.ConnectionClosedOK:
            print("Connection closed by server")

if __name__ == "__main__":
    file_path = "./录音.m4a"  # Replace with the path to your MP3 file
    asyncio.run(send_audio(file_path))
    # asyncio.run(send_audio(file_path))